package countingFileWords;

import java.awt.List;
import java.io.*;
import java.util.*;

public class CountingFileWords {

	public static void count(String src,Map<String, Integer> map) throws Exception{
		File file = new File(src);
		try {
			if(!file.exists()) {
			System.out.println("this file does not exit.");
			}
			else if(!file.canRead()) {
			System.out.println("this file can not read.");
			}
			Scanner scan = new Scanner(file);
			System.out.println(src + "-------content------");
			while(scan.hasNext()) {
				String s = scan.next();
				if(!s.matches("[a-zA-Z0-9-]+")) {
					throw new Exception("appear the disorder words.");
				}	
				if(map.containsKey(s)) {//if it has already recorded
					Integer number=map.get(s);
					number++;
					map.put(s, number);
				}
				else {
					map.put(s, 1);
				}
			}
			scan.close();
			}catch(FileNotFoundException e) {
			e.printStackTrace();
			}catch(Exception e) {
			e.printStackTrace();
			}
		System.out.println("this file is finished.");
	}
		
		
	
	public static void resualt(String filePath,Map<String, Integer> map) {
		File file = new File(filePath);
		try {
			PrintWriter out = new PrintWriter(file);
			ComparatorByValue sort = new ComparatorByValue(map);
			ArrayList<String> keys = new ArrayList<String>(map.keySet());
			Collections.sort(keys,sort);
			for(String s : keys) {
				out.println(s + " " + map.get(s));
			}
			out.close();
		}catch(FileNotFoundException e) {
			e.printStackTrace();
		}catch(Exception e) {
			e.printStackTrace();
		} 
		
}
}